package info.peigen.hotpot.common.core.logging.util;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.lang.UUID;
import org.noear.solon.core.handle.UploadedFile;

import java.io.ByteArrayInputStream;

/**
 * base64转为UploadedFile工具类
 * base64Convert
 *
 * @author peigen
 */
public class Base64ToUploadedFile {
    /**
     * base64转multipartFile
     *
     * @param base64 base64
     * @param name   文件名
     *
     * @return 上传文件对象
     */
    public static UploadedFile base64Convert(String base64, String name) {
        String[] baseStr = base64.split(",");
        byte[]   b       = Base64Decoder.decode(baseStr[1]);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(b);

        return new UploadedFile("image/jpg", byteArrayInputStream, name);
    }

    public static UploadedFile base64Convert(String base64) {
        String[] baseStr = base64.split(",");
        byte[]   b       = Base64Decoder.decode(baseStr[1]);
        for (int i = 0; i < b.length; ++i) {
            if (b[i] < 0) {
                b[i] += 256;
            }
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(b);
        return new UploadedFile("image/jpg", byteArrayInputStream, UUID.randomUUID().toString());
    }
}

